﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using yc.Dal;

namespace yc.Site
{
	public class Common
	{
		static LockList<SysDictionary> _dictionary = new LockList<SysDictionary>();
		static LockList<SysArea> _sysarea = new LockList<SysArea>();

		public readonly static IList<SelectListItem> UnSelect = new List<SelectListItem>
		{
			new SelectListItem{Text="==请选择==",Value=""},
		};

		/// <summary>
		/// 数据字典常量
		/// </summary>
		public static LockList<SysDictionary> Dictionary { get { return _dictionary; } }

		/// <summary>
		/// 系统地区信息常量
		/// </summary>
		public static LockList<SysArea> SysArea { get { return _sysarea; } }

		/// <summary>
		/// 从浏览器删除 Forms 身份验证票证
		/// </summary>
		/// <returns>用户登陆页面</returns>
		public static string SignOut()
		{
			FormsAuthentication.SignOut();
			HttpContext.Current.Session.Abandon();
			return FormsAuthentication.LoginUrl;
		}

		/// <summary>
		/// 用户登陆
		/// </summary>
		/// <param name="user">用户</param>
		/// <param name="createPersistentCookie">保存登陆状态</param>
		/// <returns>登陆前的页面</returns>
		public static string SignIn(SysUser user, bool createPersistentCookie)
		{
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, user.LoginName, DateTime.Now, DateTime.Now.AddHours(12), createPersistentCookie, user.Password, FormsAuthentication.FormsCookiePath);
			string hashTicket = FormsAuthentication.Encrypt(ticket);

			HttpCookie ticketCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket) { HttpOnly = true };
			if (createPersistentCookie) ticketCookie.Expires = DateTime.Now.AddHours(12);

			HttpContext.Current.Response.Cookies.Add(ticketCookie);
			HttpContext.Current.Session[Constants.SessionUser] = user;
			return GetRedirectUrl(true);
		}

		/// <summary>
		/// 获取跳转页面
		/// </summary>
		/// <param name="force">强制已经登陆</param>
		/// <returns></returns>
		public static string GetRedirectUrl(bool force = false)
		{
			if (force || IsAuthenticated) return FormsAuthentication.GetRedirectUrl(LoginName, true);
			return FormsAuthentication.LoginUrl;
		}

		/// <summary>
		/// 获取一个值，该值指示是否验证了用户。
		/// </summary>
		public static bool IsAuthenticated
		{
			get
			{
				return HttpContext.Current != null && (HttpContext.Current.User.Identity.IsAuthenticated || User != null);
			}
		}

		/// <summary>
		/// 获取当前用户ID
		/// </summary>
		/// <returns></returns>
		private static string getLoginName()
		{
			if (User != null) return User.LoginName;
			if (HttpContext.Current != null && HttpContext.Current.User.Identity.IsAuthenticated) return HttpContext.Current.User.Identity.Name;
			return string.Empty;
		}

		/// <summary>
		/// 登陆用户编号
		/// </summary>
		public static string LoginName
		{
			get
			{
				return getLoginName();
			}
		}

		/// <summary>
		/// 登陆用户
		/// </summary>
		public static SysUser User
		{
			get
			{
				if (HttpContext.Current.Session != null)
				{
					var _user_ = HttpContext.Current.Session[Constants.SessionUser] as SysUser;
					if (_user_ == null && HttpContext.Current.User.Identity.IsAuthenticated)
					{
						using (var db = new DBContext())
						{
							var uid = HttpContext.Current.User.Identity.Name;
							HttpContext.Current.Session[Constants.SessionUser] =
								_user_ = db.SysUser.FirstOrDefault(p => p.LoginName.Equals(uid));
						}
					}
					return _user_;
				}
				return default(SysUser);
			}
		}

		#region 区域，控制器，视图
		/// <summary>
		/// 区域
		/// </summary>
		public static string Area
		{
			get
			{
				return ((string)HttpContext.Current.Request.RequestContext.RouteData.DataTokens["area"] ?? "/").ToUpper();
			}
		}

		/// <summary>
		/// 视图
		/// </summary>
		public static string Action
		{
			get
			{
				return ((string)HttpContext.Current.Request.RequestContext.RouteData.Values["action"]).ToUpper();
			}
		}

		/// <summary>
		/// 控制器
		/// </summary>
		public static string Controller
		{
			get
			{
				return ((string)HttpContext.Current.Request.RequestContext.RouteData.Values["controller"]).ToUpper();
			}
		}
		#endregion
	}

	public class LockList<T> : List<T>
	{
		object lockObj = new object();

		public void AddRange(IEnumerable<T> source)
		{
			lock (lockObj)
			{
				base.AddRange(source);
			}
		}

		public void RemoveAll(Predicate<T> match)
		{
			lock (lockObj)
			{
				base.RemoveAll(match);
			}
		}

		public void Initialize(IEnumerable<T> source)
		{
			lock (lockObj)
			{
				base.Clear();
				base.AddRange(source);
			}
		}
	}
}